<!-- SubMeterDialog.vue -->
<template>
    <el-dialog v-model="visible" :title="meterData?.meter_code + ' 表计数据'" width="80%" destroy-on-close draggable
        :close-on-click-modal="false">
        <div class="dialog-header">
            <div class="breadcrumb-container">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item v-for="item in breadcrumbList" :key="item.id"
                        :class="{ 'clickable': item.id !== currentMeter?.id }">
                        <el-button link @click="handleBreadcrumbClick(item)">{{ item.meter_code }}</el-button>
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div style="margin-left: auto;">
                <span style="font-size: var(--font-size-small);margin-right: var(--gap-small);">表格布局</span>
                <el-segmented class="custom-style" v-model="localTableSize" :options="sizeOptions" />
            </div>
        </div>
        <vxe-table :padding="false" :size="localTableSize" :style="{ fontSize: getFontSize() }"
            :row-config="{ isCurrent: true, isHover: true }" ref="tableRef" show-overflow height="500px" border
            align="center" :data="childrenData" :loading="loading" @cell-click="handleTableRowClick">
            <!-- 固定列 -->
            <vxe-column type="seq" width="60" />
            <vxe-column tree-node fixed="left" field="meter_code" title="表计编号" width="180">
                <template #default="{ row }">
                    <div class="meter-code-cell">
                        <span :class="{ 'current-meter': row.isCurrent }">{{ row.meter_code }}</span>
                        <el-tooltip v-if="!row.isCurrent && row.customChildren?.length" :content="getChildrenInfo(row)"
                            placement="right" :show-after="100">
                            <el-tag size="small" type="info" class="children-tag">
                                {{ row.customChildren.length }}个子表
                                <el-icon>
                                    <ArrowRight />
                                </el-icon>
                            </el-tag>
                        </el-tooltip>
                        <el-tag v-if="row.isCurrent" size="small" type="success">当前表计</el-tag>
                    </div>
                </template>
            </vxe-column>
            <vxe-column fixed="left" :width="getCellWidth('supply_region')" show-overflow="tooltip" title="供应点位">
                <template #default="{ row }">
                    {{ row.supply_region || '-' }}
                </template>
            </vxe-column>
            <vxe-column :width="getCellWidth()" show-overflow="tooltip" field="installation_location" title="安装位置" />
            <vxe-column field="specification" :width="getCellWidth('spec')" title="规格" />
            <vxe-column :width="getCellWidth()" field="startReading" title="启读数"></vxe-column>
            <!-- 动态日期列 -->
            <vxe-colgroup v-for="(date, dateIndex) in dateColumns" :key="date" :title="date">
                <vxe-column :width="getCellWidth()" :field="`usage_${dateIndex}`" title="流量">
                    <template #default="{ row }">
                        {{ formatFlowValue(row[`usage_${dateIndex}`]) }}
                    </template>
                </vxe-column>
                <vxe-column :width="getCellWidth()" :field="`reading_${dateIndex}`" title="读数">
                    <template #default="{ row }">
                        {{ formatReadingValue(row[`reading_${dateIndex}`]) }}
                    </template>
                </vxe-column>
            </vxe-colgroup>
            <vxe-column fixed="right" field="sum" :width="getCellWidth()" title="总用量" />
        </vxe-table>
    </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import { formatFlowValue, formatReadingValue } from "@/utils/meterUtils";
import { handleError } from "@/utils/handleError";

const props = defineProps({
    visible: Boolean,
    meterData: Object,
    dateColumns: Array,
    tableSize: String,
    loadChildNodes: {
        type: Function,
        required: true
    },
    fetchData: {
        type: Function,
        required: true
    }
});

const emit = defineEmits(['update:visible']);
const visible = ref(false);
const loading = ref(false);
const childrenData = ref([]);
const tableRef = ref(null);
const breadcrumbList = ref([]);
const currentMeter = ref(null);

const sizeOptions = [
    { label: '紧凑', value: 'mini' },
    { label: '标准', value: 'small' },
    { label: '宽松', value: 'medium' }
];

const localTableSize = ref(props.tableSize || 'small');

// 监听 props.tableSize 的变化
watch(() => props.tableSize, (newSize) => {
    if (newSize) {
        localTableSize.value = newSize;
    }
}, { immediate: true });

// 横向滚动到最后一列的方法
const scrollToLatestColumn = async () => {
    await nextTick();
    const table = tableRef.value;
    if (table) {
        try {
            // 直接查找已知的可滚动容器
            const headerWrapper = table.$el.querySelector('.vxe-table--header-inner-wrapper');
            const bodyWrapper = table.$el.querySelector('.vxe-table--body-wrapper.body--wrapper');

            if (headerWrapper && headerWrapper.scrollWidth > headerWrapper.clientWidth) {
                const maxScrollLeft = headerWrapper.scrollWidth - headerWrapper.clientWidth;
                headerWrapper.scrollLeft = maxScrollLeft;

            }

            if (bodyWrapper && bodyWrapper.scrollWidth > bodyWrapper.clientWidth) {
                const maxScrollLeft = bodyWrapper.scrollWidth - bodyWrapper.clientWidth;
                bodyWrapper.scrollLeft = maxScrollLeft;

            }

            // 如果上面都没有滚动能力，查找其他可滚动元素
            if ((!headerWrapper || headerWrapper.scrollWidth <= headerWrapper.clientWidth) &&
                (!bodyWrapper || bodyWrapper.scrollWidth <= bodyWrapper.clientWidth)) {
                const allElements = table.$el.querySelectorAll('*');
                for (const el of allElements) {
                    if (el.scrollWidth > el.clientWidth) {
                        el.scrollLeft = el.scrollWidth - el.clientWidth;

                        break;
                    }
                }
            }

        } catch (error) {

        }
    }
};


// 获取子表信息
const getChildrenInfo = (row) => {
    if (!row.customChildren?.length) return '';
    const childrenCodes = row.customChildren
        .map(child => child.meter_code)
        .join('\n');
    return `子表列表：\n${childrenCodes}`;
};


// 获取单元格宽度
const getCellWidth = (type) => {
    switch (localTableSize.value) {
        case 'mini':
            return type === 'supply_region' ? 80 : type === 'spec' ? 60 : 60;
        case 'medium':
            return type === 'supply_region' ? 120 : type === 'spec' ? 140 : 140;
        default:
            return type === 'supply_region' ? 100 : type === 'spec' ? 100 : 100;
    }
};

// 获取字体大小
const getFontSize = () => {
    switch (localTableSize.value) {
        case 'mini':
            return '10px';
        case 'medium':
            return '18px';
        default:
            return '14px';
    }
};

// 处理面包屑点击
const handleBreadcrumbClick = (item) => {
    if (item.meter_code === currentMeter.value?.meter_code) return;

    const index = breadcrumbList.value.findIndex(i => i.meter_code === item.meter_code);
    if (index > -1) {
        breadcrumbList.value = breadcrumbList.value.slice(0, index + 1);
        currentMeter.value = item;
        loadMeterData(item);
    }
};

// 处理表格行点击
const handleTableRowClick = async ({ row }) => {
    if (!row.isCurrent && row.hasChild && row.customChildren?.length > 0) {
        currentMeter.value = row;
        breadcrumbList.value.push(row);
        await loadMeterData(row);
    }
};

// 修改 loadMeterData 函数
async function loadMeterData(meter) {
    if (!meter) return;

    loading.value = true;
    try {
        const children = await props.loadChildNodes(meter);
        const combinedData = [
            { ...meter, isCurrent: true },
            ...children.filter(Boolean)
        ];
        childrenData.value = combinedData;

        // 关键：等待数据完全渲染
        loading.value = false;  // 先结束loading
        await nextTick();       // 等待DOM更新
        await nextTick();       // 再等一个周期

        // 延迟滚动，确保表格完全渲染
        setTimeout(async () => {
            await scrollToLatestColumn();
        }, 100);
    } catch (error) {
        handleError(error, '加载数据失败');
        loading.value = false;
    }
}

// 监听对话框显示状态
watch(() => props.visible, (newVal) => {
    visible.value = newVal;
    breadcrumbList.value = [];
    if (newVal && props.meterData) {
        breadcrumbList.value = [props.meterData];
        currentMeter.value = props.meterData;
        loadMeterData(currentMeter.value);
    }
});

// 监听对话框关闭
watch(() => visible.value, (newVal) => {
    emit('update:visible', newVal);
});
</script>

<style scoped>
.dialog-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
}

.breadcrumb-container {
    flex: 1;
}

.meter-code-cell {
    display: flex;
    align-items: center;
    gap: var(--gap-small);
}

.current-meter {
    font-weight: bold;
    color: var(--el-color-primary);
}

.children-tag {
    margin-left: 4px;
}

:deep(.clickable) {
    cursor: pointer;
}

:deep(.el-dialog__body) {
    padding-top: 10px;
}

:deep(.custom-style) {
    --el-border-radius-round: 20px;
}
</style>